package de.oszimtcc.googleapi;

import java.io.IOException;
import java.util.List;

import android.app.Dialog;
import android.os.AsyncTask;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.google.api.services.calendar.Calendar;
import com.google.api.services.calendar.model.CalendarListEntry;
import com.google.api.services.calendar.model.Event;

import de.oszimtcc.timetable.TimetableApplication;


/**
 * @author reuter
 *
 */
public class LoadEventsAsync extends AsyncTask<Calendar, Event, CalendarInfo>
{

	String actualclass;
	Calendar toHandle;
	AppointmentReader calendarservice;
	CalendarInfo toReturn;
		
	public LoadEventsAsync(AppointmentReader pToHandle)
	{
		calendarservice = pToHandle;
		toHandle = pToHandle.client;
		actualclass = TimetableApplication.getInstance().getActualClass();
	}
	
	@Override
	protected void onPreExecute() 
	{
		actualclass += "+DevTest";
	}

	@Override
	protected void onCancelled() 
	{
	}

	@Override
    protected CalendarInfo doInBackground(Calendar...pCalendars)
    {
		try
		{
			List<CalendarListEntry> calendarList = toHandle.calendarList().list().execute().getItems();
			CalendarListEntry searchCalendar = null;
			int counter = 0;
			for(CalendarListEntry calendarEntry : calendarList)
            {
				counter++;
				if(isCancelled())
					return null;
				String[] splittedClassName = actualclass.split("\\+");
	            Boolean isSearchedCalendar = false;
				for(String classNameSplit : splittedClassName)
                {
	                isSearchedCalendar = calendarEntry.getSummary().contains(classNameSplit);
                }
				if(isSearchedCalendar)
				{
					searchCalendar = calendarEntry;
					break;
				}
            }
			if(searchCalendar == null)
				return null;
			
			toReturn = new CalendarInfo(searchCalendar);
			List<Event> eventList = toHandle.events().list(toReturn.getId()).execute().getItems();
			counter = 0;
			for (Event event : eventList) 
			{
				counter++;
			    toReturn.AddEvent(event);
			    publishProgress(event);
			}
			
			return toReturn;			
		}
		catch(IOException ex)
		{
			return null;
		}
    }
	
	@Override
	protected void onProgressUpdate(Event... values) 
	{
		calendarservice.onNewEventFound(values[0]);
	}

	@Override
	protected void onPostExecute(CalendarInfo result) 
	{
		
	}

}
